package org.lex.utils.logging.pattern;

import java.util.logging.LogRecord;

public abstract class NamePattern extends Pattern {
	protected int deepth = -1;

	public NamePattern(String pattern) {
		super(pattern);
		if (this.getStyles().length > 0)
			this.deepth = Integer.parseInt(this.getStyles()[0]);
		else
			this.deepth = -1;
	}

	public abstract String getName(LogRecord record);

	@Override
	public String format(LogRecord record) {
		String name = this.getName(record);
		if (-1 == deepth) {
			return name;
		} else if (0 == deepth) {
			return "";
		} else {
			int index = NamePattern.findDotIndex(name, this.deepth);
			return name.substring(index);
		}
	}

	/**
	 * e.g.: %l{2} -> "a.b.c" ==> "b.c"
	 * 
	 * @param name
	 * @param deepth
	 * @return
	 */
	private static int findDotIndex(String name, int deepth) {
		int index = name.length();
		for (int i = 0; i < deepth; i++) {
			index = name.lastIndexOf('.', index);
			if (-1 == index)
				return 0;
			else {
				index--;
			}
		}
		return index + 2;
	}
}
